/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package downloadmanager.component;

import downloadmanager.downloader.DownloadSegment;
import downloadmanager.downloader.DownloadSegmentState;
import downloadmanager.event.XEvent;
import downloadmanager.event.XEventListener;

/**
 *
 * @author Administrator
 */
public class ProgressSegment {

    private double start;
    private double end;
    private DownloadSegment segment;
    public final XEvent<Object> ValueChange = new XEvent<Object>();

    public ProgressSegment(double start, double end) {
        this.start = start;
        this.end = end;
    }

    public ProgressSegment(DownloadSegment downloadSegment) {
        this.segment = downloadSegment;
        updateAccordingTo(segment);
        downloadSegment.ValueChange.subscribe(new XEventListener<Object>() {

            public void eventFired(Object sender, Object args) {
                DownloadSegment s = (DownloadSegment) sender;
                updateAccordingTo(s);
            }
        });
    }

    private void updateAccordingTo(DownloadSegment s) {
        if (s.getState() == DownloadSegmentState.Finished) {
            this.start = s.getInitialStartPosition();
            this.end = s.getEndPosition();
        } else {
            this.start = s.getInitialStartPosition();
            this.end = s.getStartPosition();
        }
        ValueChange.fire(this, null);

    }

    /**
     * @return the start
     */
    public double getStart() {
        return start;
    }

    /**
     * @param start the start to set
     */
    public void setStart(double start) {
        this.start = start;
        ValueChange.fire(this, null);
    }

    /**
     * @return the end
     */
    public double getEnd() {
        return end;
    }

    /**
     * @param end the end to set
     */
    public void setEnd(double end) {
        this.end = end;
        ValueChange.fire(this, null);
    }

    @Override
    public String toString() {
        return String.format("[%s-%s]", start, end);
    }
}
